package com.lagou.wwyan.rpc.client;

import com.lagou.wwyan.rpc.bean.RpcRequestMonitor;

import java.util.*;
import java.util.stream.Collectors;

public class ZkRpcClientSelector implements RpcClientSelector {
    @Override
    public RpcClient select(String service, Map<String, List<RpcClient>> clientPool) {
        List<RpcClient> rpcClients = clientPool.get(service);
        if (rpcClients  == null || rpcClients.isEmpty()){
            return null;
        }
        if (rpcClients.size() ==1){
            return rpcClients.get(0);
        }

        List<RpcRequestMonitor.RequestTime> times = RpcRequestMonitor.getTimes();

        Random random = new Random();
        if (times.size() > 0) {
            Collections.sort(times);
            //响应时间最小的一个
            RpcRequestMonitor.RequestTime time0 = times.get(0);
            //响应时间最小的(可能有多个）
            List<RpcRequestMonitor.RequestTime> minTimes = times.stream().filter(time1 -> Objects.equals(time0.getTimeLength(), time1.getTimeLength())).peek(time -> {
                System.out.println("满足条件的服务："+time);
            }).collect(Collectors.toList());
            //选定一个满足条件的
            RpcRequestMonitor.RequestTime time = minTimes.size() == 1 ? minTimes.get(0) : minTimes.get(random.nextInt(minTimes.size()));

            List<RpcClient> list = rpcClients.stream()
                    .filter(rpcClient -> Objects.equals(time.getHost(), rpcClient.getHost()) && time.getPort() == rpcClient.getPort())
                    .collect(Collectors.toList());
            if (list.size()  > 1){
                //随机返回满足条件的,随机返回
                return list.get(random.nextInt(list.size()));
            }else if (list.size() == 1){
                return list.get(0);
            }
        }


        return rpcClients.get(random.nextInt(rpcClients.size()));
    }
}
